import datetime
from database_manager import DatabaseManager

class HistoryManager:
    def __init__(self, user_id=None):
        self.user_id = user_id  # 当前用户ID
        
        # 初始化数据库管理器
        self.db_manager = DatabaseManager()
    
    def add_record(self, title="", title_keywords="", news_type="", txt_content="", doc_filename=None, doc_content=None, created_at=None):
        """添加一条历史记录，将文档内容保存到数据库"""
        # 生成唯一ID
        record_id = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        
        # 获取当前时间（如果未提供）
        if created_at is None:
            created_at = datetime.datetime.now().isoformat()
        
        # 保存到数据库
        try:
            self.db_manager.cursor.execute(
                '''INSERT INTO news_history 
                (user_id, record_id, timestamp, title, title_keywords, news_type, txt_content, doc_filename, doc_content) 
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)''',
                (self.user_id, record_id, created_at, title, title_keywords, news_type, txt_content, doc_filename, doc_content)
            )
            self.db_manager.conn.commit()
        except Exception as e:
            print(f"保存到数据库失败: {e}")
            self.db_manager.conn.rollback()
    
    def get_records(self, limit=10):
        """获取历史记录"""
        if self.user_id:
            try:
                self.db_manager.cursor.execute(
                    '''SELECT * FROM news_history 
                    WHERE user_id = %s 
                    ORDER BY timestamp DESC 
                    LIMIT %s
                    ''',
                    (self.user_id, limit)
                )
                records = self.db_manager.cursor.fetchall()
                for record in records:
                    record['timestamp'] = record['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
                return records
            except Exception as e:
                print(f"从数据库获取记录失败: {e}")
                return []
        return []
    
    def get_document(self, record_id):
        """从数据库获取文档内容
        参数:
            record_id: 记录ID
        返回:
            tuple: (文档内容bytes, 文件名) 或 None
        """
        if self.user_id and record_id:
            try:
                self.db_manager.cursor.execute(
                    '''SELECT * FROM news_history 
                    WHERE user_id = %s AND record_id = %s
                    ''',
                    (self.user_id, record_id)
                )
                record = self.db_manager.cursor.fetchone()
                if record:
                    record['timestamp'] = record['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
                return record
            except Exception as e:
                print(f"从数据库获取记录失败: {e}")
                return None
        return None
    
    def delete_record(self, record_id):
        """删除单条历史记录"""
        if self.user_id and record_id:
            try:        
                self.db_manager.cursor.execute(
                    "DELETE FROM news_history WHERE record_id = %s AND user_id = %s",
                    (record_id, self.user_id)
                )
                affected_rows = self.db_manager.cursor.rowcount
                self.db_manager.conn.commit()
                return affected_rows > 0
            except Exception as e:
                self.db_manager.conn.rollback()
                return False
        print(f"删除失败：参数无效 - record_id={record_id}, user_id={self.user_id}")
        return False
    
    def clear_history(self):
        """清空数据库中的历史记录"""
        if self.user_id:
            try:
                self.db_manager.cursor.execute(
                    "DELETE FROM news_history WHERE user_id = %s",
                    (self.user_id,)
                )
                self.db_manager.conn.commit()
                return True
            except Exception as e:
                print(f"清空数据库记录失败: {e}")
                self.db_manager.conn.rollback()
                return False